package com.company.wechatpush.service;

import com.alibaba.fastjson.JSONObject;
import com.company.wechatpush.config.PushConfig;
import com.company.wechatpush.entity.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Real
 * @since 2022-09-03 1:03 AM
 */
public class TokenService {
    /**
     * 请求Token的URI
     */
    public static final String TOKEN_URI = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}";

    /**
     * 获取用户的Token值
     *
     * @return
     */
    public static Result<String> getToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>(4);
        map.put("APPID", PushConfig.getAppId());
        map.put("APPSECRET", PushConfig.getSecret());
        String res = restTemplate.getForObject(TokenService.TOKEN_URI, String.class, map);
        JSONObject json = JSONObject.parseObject(res);

        if (json == null) {
            // 接口地址有误或者接口没调通
            return Result.error(500, "Token接口请求失败，请检查接口地址！");
        }
        // {"access_token":"ACCESS_TOKEN","expires_in":7200}
        String accessToken = json.getString("access_token");
        String expiresIn = json.getString("expires_in");
        if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(expiresIn)) {
            return Result.error(500, "Token接口请求失败，请检查接口地址！");
        }
        // 失效时间
        int expire = Integer.parseInt(expiresIn);
        return Result.success(accessToken);
    }


    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    /**
     * sha1方法
     */
    public static String sha1(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        //把字符串转为字节数组
        byte[] b = data.getBytes();
        //使用指定的字节来更新我们的摘要
        md.update(b);
        //获取密文  （完成摘要计算）
        byte[] b2 = md.digest();
        //获取计算的长度
        int len = b2.length;
        //16进制字符串
        String str = "0123456789abcdef";
        //把字符串转为字符串数组
        char[] ch = str.toCharArray();
        //创建一个40位长度的字节数组
        char[] chs = new char[len * 2];
        //循环20次
        for (int i = 0, k = 0; i < len; i++) {
            //获取摘要计算后的字节数组中的每个字节
            byte b3 = b2[i];
            // >>>:无符号右移
            // &:按位与
            //0xf:0-15的数字
            chs[k++] = ch[b3 >>> 4 & 0xf];
            chs[k++] = ch[b3 & 0xf];
        }
        //字符数组转为字符串
        return new String(chs);
    }
}
